import numpy as np
import matplotlib.pyplot as mp

def Irectg(f, a, b, n):
    
    h = (b - a)/n
    I = 0
    
    for i in range(0,n):
        I += f(a + i * h)
    
    I *= h
    
    return I

def Irectd(f, a, b, n):

	h = (b - a)/n
	I = 0

	for i in range(1,n+1):
		I += f(a + i * h)

	I *= h

	return I

def Itrap(f, a, b, n):
    
    h = (b - a)/n
    I = 0
    
    for i in range(1,n):
        I += f(a + i * h)
    
    I += (f(a)+f(b))/2
    I *= h
    
    return I

def Imidpoint(f, a, b, n):
    
    h = (b - a)/n
    I = 0
    
    for i in range(0, n):
        I += f(a + i * h + h/2)
    
    I *= h
    
    return I

def Isimpson(f, a, b, n):
    
    h = (b - a)/n
    I = 0
    
    for i in range(1,n+1):
        I += (1./6.)*f(a + i*h -h) + (2./3.)*f(a + i*h -h/2.) + (1./6.)*f(a + i*h)
    
    I *= h
    
    return I


def testIntegration1(f,I, a, b):
    
    N = 100
    
    c = range(0,N)
    
    x = range(0,N)
    y = range(0,N)
    z = range(0,N)
    t = range(0,N)
    
    for i in range(1,N):
        x[i] = np.log(abs(I-Irectg(f, a, b, i)))
        y[i] = np.log(abs(I-Itrap(f, a, b, i)))
        z[i] = np.log(abs(I-Imidpoint(f, a, b, i)))
        t[i] = np.log(abs(I-Isimpson(f, a, b, i)))
    
    mp.clf()
    mp.semilogx()
    plotRect, = mp.plot(c, x, linewidth=1.0)
    plotTrap, = mp.plot(c, y, linewidth=1.0)
    plotMilieu, = mp.plot(c, z, linewidth=1.0)
    plotSimpson, = mp.plot(c, t, linewidth=1.0)
    
    mp.xlabel("N max")
    mp.ylabel("Integrale de f")
    mp.title("Tests d'integration de la fonction x^5")
    mp.legend([plotRect,plotTrap,plotMilieu,plotSimpson],["Rectangle","Trapeze","Milieu","Simpson"])
    mp.savefig("../img/x**5")
    mp.show()

def testIntegration2(f,I, a, b):
    
    N = 100
    
    c = range(0,N)
    
    x = range(0,N)
    y = range(0,N)
    z = range(0,N)
    t = range(0,N)
    
    for i in range(1,N):
        x[i] = np.log(abs(I-Irectg(f, a, b, i)))
        y[i] = np.log(abs(I-Itrap(f, a, b, i)))
        z[i] = np.log(abs(I-Imidpoint(f, a, b, i)))
        t[i] = np.log(abs(I-Isimpson(f, a, b, i)))
    
    mp.clf()
    mp.semilogx()
    plotRect, = mp.plot(c, x, linewidth=1.0)
    plotTrap, = mp.plot(c, y, linewidth=1.0)
    plotMilieu, = mp.plot(c, z, linewidth=1.0)
    plotSimpson, = mp.plot(c, t, linewidth=1.0)
    
    mp.xlabel("N max")
    mp.ylabel("Integrale de f")
    mp.title("Tests d'integration de la fonction cos(x^2)+3*x^3-14*sin(x)")
    mp.legend([plotRect,plotTrap,plotMilieu,plotSimpson],["Rectangle","Trapeze","Milieu","Simpson"])
    mp.savefig("../img/cos(x**2)+3*x**3-14*sin(x)")
    mp.show()

def test():
    
    testIntegration1(lambda x : x**5, 166666.666667, 0., 10.)
    testIntegration2(lambda x : np.cos(x**2)+3*x**3 - 14*np.sin(x),7474.85,0.,10.)
    
